package com.example.demo;


import com.example.entity.*;
import com.example.execute.PlacingFilesService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.List;

@Component
public class FileChooserUI extends JFrame {
    // 发送请求
    private static RestTemplate restTemplate;

    static {
        restTemplate = new RestTemplate();
    }

    @Autowired
    private PlacingFilesService placingFilesService;

    private JTextField folderPathField; // 选择目录文本框
    private JTextField taskNameField; // 任务名称文本框

    public static int fileNums;// 文件数
    public static long fileTotalSize;// 文件总大小
    public static String speed;// 速率
    public static double takeTime;// 用时
    public static double leftTime;// 剩余时间



    // 下拉框
    // 目标对象
    private JComboBox<DictTarget> targetObjectComboBox;
    // pdw格式
    private JComboBox<DictPwdFormat> pdwComboBox;
    // 采集地点
    private JComboBox<DictGather> gatherPlaceComboBox;
    // 系统型号
    private JComboBox<DictSystemModel> systemModelComboBox;

    // 落盘进度条
    public static JProgressBar progressBar;

//    @Autowired
//    private FtpUploadWorker ftpUploadWorker;

    public FileChooserUI() {
        System.out.println("执行ui构造器。。。。。。。。。。。。。。。");
        ImageIcon icon = new ImageIcon(System.getProperty("user.dir") + "\\upload.png");
        setIconImage(icon.getImage());
        initUI();
    }

    private void initUI() {
        setTitle("File Chooser");
        setSize(800, 260);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        // 初始化文本框
        folderPathField = new JTextField();
        folderPathField.setEditable(false);
        folderPathField.setColumns(25);

        taskNameField = new JTextField(20);
        taskNameField.setEditable(true);

        // 在构造方法中初始化进度条
        progressBar = new JProgressBar(0, 100);
        progressBar.setStringPainted(true); // 显示百分比
        progressBar.setPreferredSize(new Dimension(300, 20)); // 设置进度条的大小

        // 填充下拉框的值
        fillComBoxValue();

        JButton chooseButton = new JButton("选择目录");
        // 给选择文件按钮添加事件:选完文件夹将绝对路径展示在folderPathField中
        chooseButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JFileChooser fileChooser = new JFileChooser();
                fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

                int result = fileChooser.showOpenDialog(null);
                if (result == JFileChooser.APPROVE_OPTION) {
                    File selectedFolder = fileChooser.getSelectedFile();
                    folderPathField.setText(selectedFolder.getAbsolutePath());
                }
            }
        });


        JButton sendButton = new JButton("开始落盘");
        sendButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                // 使用 SwingWorker 执行后台任务 将 HTTP 请求放在一个独立的线程中执行，以避免阻塞主线程。
                SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
                    @Override
                    protected Void doInBackground() {
                        System.out.println("开始落盘" + Thread.currentThread().getName());
                        String folderPath = folderPathField.getText().trim();// 落盘文件目录

                        if (folderPath.isEmpty()) {
                            JOptionPane.showMessageDialog(null, "请选择文件！", "Error", JOptionPane.ERROR_MESSAGE);
                            return null;
                        }

                        DictTarget targetSelected = (DictTarget) targetObjectComboBox.getSelectedItem();// 目标对象
                        DictPwdFormat pdwSelected = (DictPwdFormat) pdwComboBox.getSelectedItem();
                        DictGather gatherSelected = (DictGather) gatherPlaceComboBox.getSelectedItem();
                        DictSystemModel systemModelSelected = (DictSystemModel) systemModelComboBox.getSelectedItem();

                        // 1落盘文件
                        String url = "http://localhost:9988/file/in/gatherFiles";

                        // 构建URL
                        UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url)
                                .queryParam("dirPath", folderPath)
                                .queryParam("gatherId", gatherSelected.getId())
                                .queryParam("pdwFormatId", pdwSelected.getId())
                                .queryParam("systemModelId", systemModelSelected.getId())
                                .queryParam("taskName", taskNameField.getText())
                                .queryParam("targetId", targetSelected.getId());

                        // 发送落盘文件请求
                        ResponseResult result = restTemplate.getForObject(builder.toUriString(), ResponseResult.class);
                        JOptionPane.showMessageDialog(null, result.getMessage(), "结果", JOptionPane.INFORMATION_MESSAGE);

                        return null;
                    }

                    @Override
                    protected void done() {
                        // 后台任务完成后的回调，可以在这里更新 UI
                        // 例如，关闭进度条等
                    }
                };

                // 执行 SwingWorker
                worker.execute();

//                JOptionPane.showMessageDialog(null, result.getMessage(), "结果", JOptionPane.INFORMATION_MESSAGE);
            }
        });

        folderPathField.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
                updateTaskNameField();
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                updateTaskNameField();
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                updateTaskNameField();
            }
        });

        targetObjectComboBox.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                updateTaskNameField();
            }
        });

        pdwComboBox.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                updateTaskNameField();
            }
        });

        gatherPlaceComboBox.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                updateTaskNameField();
            }
        });

        systemModelComboBox.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                updateTaskNameField();
            }
        });


        // 设置布局为BorderLayout
        setLayout(new BorderLayout());

        // 创建垂直的Box容器
        Box vBox = Box.createVerticalBox();
        Box hBox1 = Box.createHorizontalBox();

        // 创建面板用于放置选择文件相关组件
        JPanel choosePanel = new JPanel();
        choosePanel.add(chooseButton);
        choosePanel.add(folderPathField);

        JPanel taskNamePanel = new JPanel();
        taskNamePanel.add(new JLabel("任务名称："));
        taskNamePanel.add(taskNameField);
        hBox1.add(taskNamePanel);
        hBox1.add(choosePanel);


        // 创建水平的Box容器
        Box hBox2 = Box.createHorizontalBox();
        // 创建面板用于放置目标对象下拉框
        JPanel targetComBox = new JPanel(new FlowLayout(FlowLayout.CENTER, 5, 5));
        targetComBox.add(new JLabel("目标对象:"));
        targetComBox.add(targetObjectComboBox);
        hBox2.add(targetComBox);


        // 创建面板用于放置pdw格式下拉框
        JPanel pdwComBox = new JPanel(new FlowLayout(FlowLayout.CENTER, 5, 5));
        pdwComBox.add(new JLabel("pdw格式:"));
        pdwComBox.add(pdwComboBox);
        hBox2.add(pdwComBox);

        // 参数3下拉框
        JPanel comBox3 = new JPanel(new FlowLayout(FlowLayout.CENTER, 5, 5));
        comBox3.add(new JLabel("采集地点:"));
        comBox3.add(gatherPlaceComboBox);
        hBox2.add(comBox3);

        // 参数4下拉框
        JPanel comBox4 = new JPanel(new FlowLayout(FlowLayout.CENTER, 5, 5));
        comBox4.add(new JLabel("系统型号:"));
        comBox4.add(systemModelComboBox);
        hBox2.add(comBox4);

        Box hBox2_3 = Box.createHorizontalBox();
        JLabel fileNumLabel = new JLabel();
        JLabel fileTotalSizeLabel = new JLabel();
        JLabel speedLabel = new JLabel();
        JLabel takeTimeLabel = new JLabel();
        JLabel leftTimeLabel = new JLabel();
        hBox2_3.add(fileNumLabel);
        hBox2_3.add(Box.createHorizontalStrut(20));
        hBox2_3.add(fileTotalSizeLabel);
        hBox2_3.add(Box.createHorizontalStrut(20));
        hBox2_3.add(speedLabel);
        hBox2_3.add(Box.createHorizontalStrut(20));
        hBox2_3.add(takeTimeLabel);
        hBox2_3.add(Box.createHorizontalStrut(20));
        hBox2_3.add(leftTimeLabel);

        // 定时器监控文件上传指标数据
        Timer timer = new Timer(1000, e -> {
            // 在Swing 的事件分派线程中更新标签文本
            SwingUtilities.invokeLater(() -> {
                if(fileNums != 0) fileNumLabel.setText("文件数：" + fileNums);
                if(fileTotalSize != 0) fileTotalSizeLabel.setText("文件大小：" + fileTotalSize + "KB");
                if(speed != null) speedLabel.setText("速率：" + speed);
                if(takeTime != 0) takeTimeLabel.setText("用时：" + (takeTime / 100) + "s");
                if(leftTime != 0) leftTimeLabel.setText("剩余时间：" + leftTime + "s");
            });
        });

        // 启动定时器
        timer.start();

        // 进度条
        Box hBox3 = Box.createHorizontalBox();
        hBox3.add(progressBar);

        vBox.add(hBox1);
        vBox.add(hBox2);
        vBox.add(hBox2_3);
        vBox.add(hBox3);

        // 将选择文件相关组件放在北部，开始落盘按钮放在南部
        add(vBox, BorderLayout.CENTER);

        JPanel sendPanel = new JPanel();
        sendPanel.add(sendButton);
        add(sendPanel, BorderLayout.SOUTH);

        setVisible(true);
    }

    /**
     * 初始化下拉框的值
     */
    private void fillComBoxValue() {
        // 调用接口获取下拉框的中的值
        List<DictTarget> targetList = null;
        List<DictGather> gatherList = null;
        List<DictPwdFormat> pdwList = null;
        List<DictSystemModel> systemModelList = null;
        try {
            targetList = getTargetValues();
            gatherList = getGatherValues();
            pdwList = getPdwValues();
            systemModelList = getSystemModelValues();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 目标对象下拉框
        targetObjectComboBox = new JComboBox<>();
        pdwComboBox = new JComboBox<>();
        gatherPlaceComboBox = new JComboBox<>();
        systemModelComboBox = new JComboBox<>();


        for (DictTarget target : targetList) {
            targetObjectComboBox.addItem(target);
        }
        for (DictGather dictGather : gatherList) {
            gatherPlaceComboBox.addItem(dictGather);
        }
        for (DictPwdFormat dictPwdFormat : pdwList) {
            pdwComboBox.addItem(dictPwdFormat);
        }
        for (DictSystemModel dictSystemModel : systemModelList) {
            systemModelComboBox.addItem(dictSystemModel);
        }
    }


    /**
     * 更新任务名称
     */
    private void updateTaskNameField() {
        // Check if all JComboBox instances have selections
        if (targetObjectComboBox.getSelectedItem() != null &&
                pdwComboBox.getSelectedItem() != null &&
                gatherPlaceComboBox.getSelectedItem() != null &&
                systemModelComboBox.getSelectedItem() != null &&
                folderPathField.getText() != null) {

            String selectedValues =
                    folderPathField.getText() + "_" +
                            targetObjectComboBox.getSelectedItem().toString() + "_" +
                            pdwComboBox.getSelectedItem().toString() + "_" +
                            gatherPlaceComboBox.getSelectedItem().toString() + "_" +
                            systemModelComboBox.getSelectedItem().toString();
            taskNameField.setText(selectedValues);
        }
    }

    /**
     * 获取目标对象下拉框的值
     *
     * @return
     * @throws IOException
     */
    public List<DictTarget> getTargetValues() throws IOException {
        String url = "http://localhost:9988/dict/target";

        ResponseEntity<ApiResponse<DictTarget>> responseEntity = restTemplate.exchange(
                url,
                HttpMethod.GET,
                null,
                new ParameterizedTypeReference<ApiResponse<DictTarget>>() {
                }
        );

        ApiResponse<DictTarget> apiResponse = responseEntity.getBody();
        List<DictTarget> targetList = apiResponse.getDataList();

        return targetList;
    }

    /**
     * 获取采集地点下拉框的值
     */
    private List<DictGather> getGatherValues() {
        String url = "http://localhost:9988/dict/gather/list";

        ResponseEntity<ApiResponse<DictGather>> responseEntity = restTemplate.exchange(
                url,
                HttpMethod.GET,
                null,
                new ParameterizedTypeReference<ApiResponse<DictGather>>() {
                }
        );

        ApiResponse<DictGather> apiResponse = responseEntity.getBody();
        return apiResponse.getDataList();
    }

    /**
     * 获取pdw格式下拉框的值
     */
    private List<DictPwdFormat> getPdwValues() {
        String url = "http://localhost:9988/dict/pwd/format/list";

        ResponseEntity<ApiResponse<DictPwdFormat>> responseEntity = restTemplate.exchange(
                url,
                HttpMethod.GET,
                null,
                new ParameterizedTypeReference<ApiResponse<DictPwdFormat>>() {
                }
        );

        ApiResponse<DictPwdFormat> apiResponse = responseEntity.getBody();
        return apiResponse.getDataList();
    }

    /**
     * 获取系统型号下拉框的值
     */
    private List<DictSystemModel> getSystemModelValues() {
        String url = "http://localhost:9988/dict/system/model/list";

        ResponseEntity<ApiResponse<DictSystemModel>> responseEntity = restTemplate.exchange(
                url,
                HttpMethod.GET,
                null,
                new ParameterizedTypeReference<ApiResponse<DictSystemModel>>() {
                }
        );

        ApiResponse<DictSystemModel> apiResponse = responseEntity.getBody();
        return apiResponse.getDataList();
    }

    public static void main(String[] args) {
//        SwingUtilities.invokeLater(() -> {
//            new FileChooserUI();
//        });
        new FileChooserUI();
    }

}
